<template>
	<view>
		<view class="content">
			<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</u-navbar>


			<view class="flex-auto">
				<view class="topMainForm f-dc"
					style="padding: 20rpx;max-height: 30vh;position: relative;background-color: #fff;">
					<view class="content_main_CardBox"
						style="border-radius: 15rpx;background-color: #4499ec;flex: 1;overflow: auto;padding: 20rpx 30rpx;color: #fff;">
						<view class="x-f" style="font-size: 28rpx;padding: 8rpx 0;font-weight: 600;">
							<text>No:{{formData.BillNO}}</text>
						</view>
						<view style="font-size: 20rpx;" class="f-dc">
							<view style="margin-bottom: 6rpx;">
								<text>产品信息：{{formData.ProductCode + '__' + formData.ProductName}}</text>
							</view>
							<view style="margin-bottom: 6rpx;">
								<text>产品规格：{{formData.ProductSpec}}</text>
							</view>
							<view class="x-f" style="margin-bottom: 6rpx;">
								<view>
									<text>样品数：</text>
									<text>{{formData.BJNum}}</text>
								</view>
								<view style="margin-left: 15px;">
									<text>抽检数：</text>
									<text>{{formData.CJNum}}</text>
								</view>
								<view style="margin-left: 15px;">
									<text>拒收数：</text>
									<text>{{formData.RejectionNum}}</text>
								</view>
							</view>
							<view style="margin-bottom: 6rpx;">负责人员：{{formData.CuratorName}}</view>
							<view style="margin-bottom: 6rpx;">检验方案：{{formData.ProjectName}}</view>
							<view v-if="formData.TestEndTime" style="margin-bottom: 6rpx;">检验期限：{{formData.TestEndTime}}
							</view>

						</view>

						<u-tag :plain-fill="true" plain :text="formData.SFJYState" style="position: absolute;top: 10px;right: 10px;"></u-tag>

						<!-- 已审核标记 -->
						<!-- <uni-icons fontFamily="CustomFontPlatform" color="#b3ffd6"
						style="position: absolute;right: 20rpx;top: 20rpx;"
						size="100rpx">{{$utils.toUniCode('&#xeda6;')}}</uni-icons> -->
					</view>
				</view>
				<!-- 任务进度 -->


				<view style="padding: 7rpx 15rpx 15rpx;">

					<view class="child-card" v-for="(item, index) in tableData" :key="item.LabTestProductDeID">
						<!-- 顶部信息 -->
						<view class="child-card-top">
							<view class="child-card-top__left">
								<view class="ordinal">{{ index + 1 }}</view>
								<view class="title">{{ item.LabTestPlanContent }}</view>
							</view>
						</view>

						<!-- 检验轮次组 -->
						<view class="sample-list" v-if="item.Details && item.Details.length">

							<view class="sample-box" @click="openReportTable(sample)"
								v-for="(sample, sIndex) in item.Details" :key="sIndex">
								<view class="sample-header x-f">
									<!-- 折叠控制按钮 -->
									<view class="toggle-btn"
										@click.stop="toggleCollapse(sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID)">
										{{ collapseStatus[sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID] ? '展开' : '收起' }}
									</view>


									<text>{{ sample.LabTestProjectName }}</text>
									<u-tag :text="sample.Result" style="margin-left: 10px;"
										:type="sample.FResult == 1 ? 'success' : sample.FResult == 0 ? 'error' : 'warning'"
										size="mini"></u-tag>
									<!-- Result -->
									<!-- <view style="font-size: 24rpx;">
										<text>检验次数：</text>
										<text>{{sample.ResultList.length}}</text>
									</view> -->


								</view>
								<view @click.stop="openMoreListTablePopup(sample)" class="readMore"
									v-if="sample.ResultList.length > 3">
									<text>查看更多>></text>
								</view>

								<!-- 样品检验结果表格 -->
								<uni-table border stripe emptyText="暂无更多数据"
									v-if="!collapseStatus[sample.LabTestProductItemDeID +'_' +sample.LabTestProjectID]">
									<!-- 表头行 -->
									<uni-tr>
										<uni-th align="left" width="80rpx">样品</uni-th>
										<uni-th align="left" width="200rpx">
											<view style="zoom: 0.8;">
												<text>下极限</text>
												<text style="margin: 0 4px;">/</text>
												<text>标准值</text>
												<text style="margin: 0 4px;">/</text>
												<text>上极限</text>
											</view>
										</uni-th>
										<uni-th align="left" width="100rpx">检验数据</uni-th>
										<uni-th align="left" width="100rpx">检验结果</uni-th>
										<uni-th align="left">检测工具</uni-th>
									</uni-tr>
									<!-- 表格数据行 -->
									<uni-tr v-for="(row,inx) in sample.ResultList" v-if="inx <=2">
										<uni-td width="80rpx">{{row.YPMC}}</uni-td>
										<uni-td width="200rpx">
											<view class="x-sec" style="width: 100%;zoom: 0.8;">
												<text>{{row.PoorNormally || 'NaN'}}</text>
												<text>/</text>
												<text>{{row.JYBZ || 'NaN'}}</text>
												<text>/</text>
												<text>{{row.PoorWork || 'NaN'}}</text>
											</view>
										</uni-td>
										<uni-td width="100rpx">{{row.JYJG1 || '-'}}</uni-td>
										<uni-td width="100rpx">{{row.Result || '-'}}</uni-td>
										<uni-td>{{row.ApplianceTypeName}}</uni-td>
									</uni-tr>

								</uni-table>


							</view>
						</view>
					</view>


				</view>
			</view>

			<!-- <view class="content_bottom1 x-ec" :style="$utils.disposeSafeBottomFun()">
				<view class="x-ec">
				</view>
			</view> -->

		</view>


		<uni-popup ref="popup_table" type="bottom" border-radius="10px 10px 0 0">
			<view class="f-dc" style="height: 60vh;background-color: #fff;" :style="$utils.disposeSafeBottomFun()">
				<u-navbar :fixed="false" left-text="更多" left-icon="" :autoBack="false" :safeAreaInsetTop="false"
					leftIconColor="#fff">
				</u-navbar>

				<uni-table style="flex: 1;" border stripe emptyText="暂无更多数据">
					<!-- 表头行 -->
					<uni-tr class="sticky-header">
						<uni-th align="left">样品</uni-th>
						<uni-th align="left" width="200rpx">
							<view style="zoom: 0.8;">
								<text>下极限</text>
								<text style="margin: 0 4px;">/</text>
								<text>标准值</text>
								<text style="margin: 0 4px;">/</text>
								<text>上极限</text>
							</view>
						</uni-th>
						<uni-th align="left">检验数据</uni-th>
						<uni-th align="left" width="100rpx">检验结果</uni-th>
						<uni-th align="left">检测工具</uni-th>
					</uni-tr>
					<!-- 表格数据行 -->
					<uni-tr v-for="(row,inx) in moreListTableData">
						<uni-td>{{row.YPMC}}</uni-td>
						<uni-td width="200rpx">
							<view class="x-sec" style="width: 100%;zoom: 0.8;">
								<text>{{row.PoorNormally || 'NaN'}}</text>
								<text>/</text>
								<text>{{row.JYBZ || 'NaN'}}</text>
								<text>/</text>
								<text>{{row.PoorWork || 'NaN'}}</text>
							</view>
						</uni-td>
						<uni-td>{{row.JYJG1 || '-'}}</uni-td>
						<uni-td width="100rpx">{{row.Result || '-'}}</uni-td>
						<uni-td>{{row.ApplianceTypeName}}</uni-td>
					</uni-tr>

				</uni-table>

			</view>
		</uni-popup>

		<m-pda-scancode v-if="$utils.isPda()" :listenName="pdaListenCurrent"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

		<m-loading :text="loadingText" v-model="showMLoading" :showClose="false" :loaderActive="loaderActive"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;
	export default {
		data() {
			return {
				LabTestProductID: null, // 主键ID
				enabledSubmitBtn: false, // 控制按钮是否启用
				showMLoading: false, // 加载动画
				loadingText: "正在渲染",
				loaderActive: "loading",

				titleName: "实验室检验明细",

				formData: {
					ObjectName: '',
					BillNo: '',
					Inspection: '',
					InspectionPrice: '',
				},
				TabList: [{
					title: "任务进度"
				}, {
					title: "任务记录"
				}],
				tabCurrent: 0,

				tableData: [], // 列表数据
				moreListTableData: [],
				collapseStatus: {}, // 用于存储每个样品表格的折叠状态

				ChoiceDataData: null, // 测试树形的选中数据
			};
		},
		computed: {
			selectTreeListenCurrent() { // 树型选择监听器名称
				let routes = getCurrentPages(); //当前页面栈
				return "selectTree" + routes.length;
			},

			pdaListenCurrent() { // pda监听器名称
				let routes = getCurrentPages(); //当前页面栈
				// pda监听器
				return "pdaScanCode" + routes.length;
			},
		},
		onReady() {},
		onLoad(option) {
			this.LabTestProductID = option.LabTestProductID;

			this.getPageInfoByID();
		},
		mounted() {
			let that = this;
			that.$nextTick(() => {
				that.enabledSubmitBtn = true;
			});


			uni.$on(that.selectTreeListenCurrent, (ret => {
				console.log(ret);
				if (ret.chooseType == 1) {
					that.ChoiceDataData = ret.data.EquipmentID
				} else {
					that.ChoiceDataData = ret.data.map(item => {
						return item.EquipmentID
					})
				}
				// that.$utils.layer.alert(JSON.stringify(ret))
			}));

			uni.$on("refresh_labReort", (ret) => {
				that.getPageInfoByID();
				uni.$emit("refreshToLabReport_list")
			})

			// 组件中监听队列完成
			this.$onQueueEvent('queueEmpty', () => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				console.log('页面所有请求完成');

				that.$utils.hideLoading();
				this.showMLoading = false;
				that.enabledSubmitBtn = true; // 解开按钮限制
			});

			this.$onQueueEvent('requestFail', (ret) => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				console.log('edit_requestFail');
				console.log(ret);

			});
		},
		onUnload() {
			uni.$off("refresh_labReort");
			uni.$off(this.selectTreeListenCurrent);
		},
		methods: {
			// tabs标签
			clickTabItem(data) {
				let that = this;
				this.tabCurrent = data.index;
			},

			// 映射
			getColor(FResult) {
				switch (FResult) {
					case 1:
						return '#4caf50'; // 合格
					case 0:
						return '#f44336'; // 不合格
					case 99:
						return '#ff9800'; // 待检验
					default:
						return '#cccccc'; // 未知
				}
			},

			genGradient(nood) {
				if (!nood || nood.length === 0) return '';

				const total = nood.length;
				const percentUnit = 100 / total;

				const gradientParts = nood.map((item, index) => {
					const color = this.getColor(item);
					const start = (index * percentUnit).toFixed(2);
					const end = ((index + 1) * percentUnit).toFixed(2);
					return `${color} ${start}%, ${color} ${end}%`;
				});

				return `linear-gradient(to right, ${gradientParts.join(', ')})`;
			},

			toggleCollapse(key) {
				console.log(key);
				// 如果是首次点击，初始化状态为展开（因为默认是折叠）
				if (this.collapseStatus[key] === undefined) {
					this.$set(this.collapseStatus, key, false);
				} else {
					// 切换状态
					this.$set(this.collapseStatus, key, !this.collapseStatus[key]);
				}
			},

			// 取值
			getPageInfoByID() { // 根据LabTestProductID获取页面信息
				let that = this;

				that.$request("Qu_LabTestSelectDetails", {
					LabTestProductID: that.LabTestProductID
				}, function(ret) {
					console.log(ret.data);
					if (ret.status == 200) {
						let {
							ds,
							ds1,
							ds2,
							ds3
						} = ret.data;
						console.log(ds);
						if (ds.length) {
							Object.assign(that.formData, ds[0]);
						}

						// let mergeData = that.mergeAllDataFast(ds1, ds2, ds3);
						let mergeData = that.processLabTestData({
							ds1,
							ds2,
							ds3
						});
						console.log(mergeData);

						that.tableData = mergeData;
						// 初始化折叠状态 - 默认全部折叠
						mergeData.forEach(item => {
							item.Details.forEach(sample => {
								let key = sample.LabTestProductItemDeID + '_' + sample
									.LabTestProjectID;
								that.$set(that.collapseStatus, key, true);
							});
						});
					}
				})
			},

			processLabTestData(data) {
				const {
					ds1,
					ds2,
					ds3
				} = data;




				// ✅ 提前缓存 ds2 的 ID 列表，提升判断效率
				const ds2IdSet = new Set(ds2.map(item => item.LabTestProductItemDeID));

				// 第一步：合并ds2和ds3为rootMap（修正版）
				const rootMap = new Map();

				[...ds2, ...ds3].forEach(item => {
					const id = item.LabTestProductItemDeID;
					const isRoot = ds2IdSet.has(id); // 是否为ds2的主项（root）

					// 初始化rootMap：仅用ds2的项作为主项（无YPMC）
					if (isRoot && !rootMap.has(id)) {
						rootMap.set(id, {
							...item,
							ResultList: [] // 初始化空数组，用于存放ds3的关联项
						});
					}

					// 仅将ds3中含YPMC且关联ds2主项的项加入ResultList
					if (!isRoot) return; // 非ds2主项ID的项不处理
					if (item.YPMC) { // 若为ds3的项（含YPMC）且关联主项ID
						const rootItem = rootMap.get(id);
						rootItem.ResultList.push(item);
					}
				});

				// ✅ 获取合并后数组（保留属于 ds2 的主项）
				const mergedData = Array.from(rootMap.values()).filter(item =>
					ds2IdSet.has(item.LabTestProductItemDeID)
				);


				// ✅ 第二步：组装回 ds1 中，以 LabTestProductDeID 为关联键
				const resultData = JSON.parse(JSON.stringify(ds1));
				const processedMap = new Map();

				mergedData.forEach(item => {
					const key = item.LabTestProductDeID;
					if (!processedMap.has(key)) {
						processedMap.set(key, []);
					}
					processedMap.get(key).push(item);
				});

				resultData.forEach(item => {
					item.Details = processedMap.get(item.LabTestProductDeID) || [];
				});

				console.log(resultData);

				return resultData;
			},
			mergeAllDataFast(ds1, ds2, ds3) {
				// Step 1：构建 ds2 映射（按 LabTestProductDeID）
				const ds2Map = new Map();
				for (let i = 0; i < ds2.length; i++) {
					const d = ds2[i];
					const key = d.LabTestProductDeID;
					if (!ds2Map.has(key)) ds2Map.set(key, []);
					ds2Map.get(key).push(d);
				}

				// Step 2：构建 ds3 映射（按 LabTestProductItemDeID -> Times -> nood[]）
				const ds3NestedMap = new Map();
				for (let i = 0; i < ds3.length; i++) {
					const r = ds3[i];
					const itemId = r.LabTestProductItemDeID;
					const times = r.Times || 0;

					if (!ds3NestedMap.has(itemId)) ds3NestedMap.set(itemId, new Map());
					const timeMap = ds3NestedMap.get(itemId);

					if (!timeMap.has(times)) timeMap.set(times, []);
					timeMap.get(times).push(r);
				}

				// Step 3：组装最终结构
				const result = ds1.map(main => {
					const details = ds2Map.get(main.LabTestProductDeID) || [];

					const newDetails = details.map(detail => {
						const itemId = detail.LabTestProductItemDeID;
						const timeMap = ds3NestedMap.get(itemId) || new Map();

						const resultList = Array.from(timeMap.entries())
							.map(([Times, nood]) => {
								// 统计字段
								let Qualified = 0;
								let Unqualified = 0;
								let Waiting = 0;

								for (const r of nood) {
									if (r.FResult === 1) Qualified++;
									else if (r.FResult === 0) Unqualified++;
									else if (r.FResult === 99) Waiting++;
								}

								return {
									Times,
									Total: nood.length,
									Qualified,
									Unqualified,
									Waiting,
									nood,
								};
							})
							.sort((a, b) => a.Times - b.Times);

						return {
							...detail,
							ResultList: resultList
						};
					});

					return {
						...main,
						Details: newDetails
					};
				});

				return result;
			},

			// 交互事件
			openReportTable(item) { // 点击进入任务表格详情
				console.log(item);

				uni.hideToast();

				plus.screen.lockOrientation('landscape-primary');

				setTimeout(() => {
					uni.navigateTo({ // 前往表单界面 lucksheet
						url: '/st_qms/LabReport/DocumentPageByReport' +
							'?keyID=' + item.LabTestProductID +
							'&keyDeID=' + item.LabTestProductDeID +
							'&MeasureTypeID=' + item.MeasureTypeID
					});
				}, 300)
			},
			openMoreListTablePopup(data) {
				this.moreListTableData = data.ResultList;

				this.$refs.popup_table.open();
			},
			changeApprove() {
				let that = this;
				if (!this.enabledSubmitBtn) {
					return;
				}
				this.enabledSubmitBtn = false;
				this.loadingText = "正在撤审";
				this.showMLoading = true;
				this.loaderActive = "loading";

				setTimeout(() => {
					that.loadingText = "已撤审";
					that.loaderActive = "success";
					setTimeout(() => {
						that.enabledSubmitBtn = true;
						that.showMLoading = false;
					}, 1000);
				}, 1000);

			},
			viewToSPC() { // 查看SPC图表
				console.log(this.formData);
				const {
					LabTestProductID
				} = this.formData;

				uni.navigateTo({
					url: "/st_qms/spc/index" + "?LabTestProductID=" + LabTestProductID
				});
			},


			openBaseScreenByTree(str, type) { // 树型
				let that = this;

				let config = {
					requestType: "$request", // 请求方法
					chooseType: type, // 是否单选
					colName: str, // 返回标识

					showSearch: true, // 是否可搜索
					SearchKey: "SearchKey",
					cmd: "getEquipmentBySBFLID", // 接口名
					keyName: "EquipmentName", // 显示值
					keyValue: "EquipmentID", // 隐藏值
					ChoiceDataData: this.ChoiceDataData || null,
					isPaging: true, // 是否分页
					pageIndexStr: "pageIndex",
					param: {
						SearchKey: "",
						EquipmentTypeID: '',
						pageIndex: 1,
						pageSize: 30,
					},
					subText: [{
						label: "编号：",
						labelKey: "EquipmentCode"
					}, {
						label: "规格：",
						labelKey: "EquipmentSpec"
					}, ],

					treeCofig: { // 树型的参数
						treeRequestType: "$request", // 请求方法
						treePath: "sbfl_XL", // 树接口名
						treeDisplayValue: "EquipmentTypeName",
						treeHiddenValue: "EquipmentTypeID",
						treeParentValues: "UpID",
						treeParams: {}
					},

				};

				that.$store.commit("ChangeAndSetStateData", {
					Name1: "BaseScreenParmByTree",
					data: config
				})

				console.log(config);
				uni.navigateTo({
					url: "/commonPage/Tool/baseScreenByTree" + "?listen=" + that.selectTreeListenCurrent
				})
			},
		}
	}
</script>

<style lang="scss">
	.sticky-header {
		position: sticky;
		top: 0;
		/* 固定在顶部 */
		z-index: 100;
		/* 确保表头在滚动时覆盖数据行 */
		background-color: #fff;
		/* 背景色避免透明 */
	}

	.toggle-btn {
		// margin-left: auto;
		color: #4499ec;
		font-size: 14px;
		padding: 0 10rpx;
	}

	.content {

		.form {
			background-color: #fff;
			padding: 15rpx;
		}

		.child-card {
			margin: 20rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

			&-top {
				display: flex;
				justify-content: space-between;
				align-items: center;

				&__left {
					display: flex;
					align-items: center;

					.ordinal {
						width: 40rpx;
						height: 40rpx;
						background: #007aff;
						color: #fff;
						border-radius: 50%;
						text-align: center;
						line-height: 40rpx;
						margin-right: 12rpx;
						font-size: 24rpx;
					}

					.title {
						font-size: 28rpx;
						font-weight: 600;
						color: #333;
					}
				}

				&__right {
					display: flex;
					align-items: center;
				}
			}

			.sample-list {
				margin-top: 16rpx;

				.sample-box {
					margin-top: 20rpx;
					border-top: 1rpx solid #eee;
					padding: 10rpx;
					border-radius: 10rpx;
					background-color: #eaf5f7;
					position: relative;

					.readMore {
						font-size: 12px;
						color: #4499ec;
						font-weight: 400;
						padding: 10px;
						position: absolute;
						top: 0;
						right: 0;
						min-width: 100px;
						height: 40px;
						line-height: 30px;
						// background-color: #40d37d;
						text-align: right;
					}

					.sample-scroll-list {
						background-color: #e8e8e8;
						padding: 10rpx;

						.sample-card {
							padding: 15rpx;
							background-color: #fff;
							min-width: 500rpx;
							min-height: 200rpx;
							margin: 10rpx;
							border-radius: 10rpx;
							zoom: 0.8;

							.sample-card__title {
								font-size: 28rpx;
								font-weight: 600;
								color: #3555ed;
								border-bottom: 1px solid #e8e8e8;
							}

							.sample-card__connect {
								padding: 10rpx 0;

								.result-bar {
									width: 100%;
									height: 30rpx;
									border-radius: 8rpx;
									background-size: 100% 100%;
									background-repeat: no-repeat;
									margin: 10rpx 0;
								}

								.sample-bottom {
									.sample-card__connect__cell {
										position: relative;
										padding-left: 20rpx !important;

										.sample-card__connect__cell-label {
											&::before {
												content: "";
												position: absolute;
												left: 0;
												top: 50%;
												transform: translateY(-50%);
												bottom: 0;
												width: 14rpx;
												height: 8rpx;
												border-radius: 1rpx;
											}

											&.green::before {
												background-color: #00c853;
											}

											&.red::before {
												background-color: #ff1744;
											}

											&.orange::before {
												background-color: #ffa000;
											}
										}
									}
								}

								.sample-card__connect__cell {
									padding: 8rpx 0;
									flex: 1;

									.sample-card__connect__cell-label {
										color: #949494;

									}

									.sample-card__connect__cell-value {
										flex: 1;
										color: #333;
										font-weight: 600;
										margin-left: 10rpx;
									}
								}
							}
						}
					}


					.sample-header {
						font-size: 26rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 10rpx;
					}

					.group-box {
						max-height: 300rpx;
						overflow-y: auto;
						background: #f9f9f9;
						border-radius: 10rpx;
						margin-top: 12rpx;
						padding: 16rpx;

						.group-header {
							font-size: 24rpx;
							margin-bottom: 10rpx;

							.group-title {
								font-weight: 600;
								color: #4863ff;
							}

							.group-stat {
								font-size: 22rpx;
								color: #888;
								margin-top: 4rpx;
								margin-left: 10rpx;
							}
						}

						.result-tag-list {
							display: flex;
							flex-wrap: wrap;
							gap: 12rpx;
							margin-top: 10rpx;
						}

						.result-tag {
							width: 20px;
							height: 20px;
							border-radius: 4px;
							font-size: 12px;
							font-weight: bold;
							color: #fff;
							text-align: center;
							line-height: 20px;

							&.ok {
								background-color: #4caf50; // 绿
							}

							&.fail {
								background-color: #f44336; // 红
							}

							&.pending {
								background-color: #ff9800; // 橙
							}
						}
					}
				}
			}
		}



		.content_bottom1 {
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			height: 70px;
			line-height: 70px;
			padding: 6px 15px;
			border-top: 2px solid #f2f2f2;

			.workBtn {
				border-color: #ddd !important;
				margin-left: 10px !important;

				&.small-font {
					font-size: 12px !important;
				}

				&:not(.small-font) {
					font-size: 14px;
				}
			}
		}
	}
</style>